import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:universal_platform/universal_platform.dart';
import '../config/AppConst.dart';
import '../generated/l10n.dart';
import '../pages/HelpPage.dart';
import '../pages/WebPage.dart';
import '../utils/AudioUtils.dart';
import '../utils/ClickUtils.dart';
import '../utils/SpUtils.dart';

import '../main.dart';
import '../pages/LanguagePage.dart';
import '../routers/router.dart';
import '../utils/CommUtils.dart';
import 'My.dart';
import 'package:url_launcher/url_launcher.dart';

const double boxDistance = 12.0;
//const int hight = 350;

//设置弹窗
class Seting extends StatefulWidget {
  final CallBack? callback;
  //true要重新开始功能
  bool isReStart = false;
  Seting({Key? key, this.callback, this.isReStart = false}) : super(key: key);
  @override
  State<Seting> createState() => GamePageState();
}

bool _isVoice = true;
bool? _isBGvocie = true;

String? Verison;

class GamePageState extends State<Seting> {
  @override
  void initState() {
    bool? isvoice = SpUtils.getInstance()?.getBool2(AppConst.voice);
    if (isvoice != null) {
      _isVoice = isvoice;
    }
    _isBGvocie = SpUtils.getInstance()?.getBool2(AppConst.bgvoice);

    CommUtils.getVerison().then((value) {
      Verison = value;
      // print("版本号:${value}");
    });
  }

  @override
  Widget build(BuildContext context) {
    double wight = CommUtils.getWidth(context);
    double hight = CommUtils.getHeight(context);
    return Wrap(
      children: [
        Container(
          //高度自适应
          // height: ScreenUtil().setHeight(wight * 0.55),
          // width: ScreenUtil().setHeight(wight * 0.5),
          decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage('assets/images/bg_seting.png'),
                fit: BoxFit.fill),
          ),
          child: Padding(
            padding: EdgeInsets.only(
              left: wight * 0.05,
              top: hight * 0.01,
              right: wight * 0.05,
            ),
            child: Column(
              children: [
                Container(
                  // height: hight * 0.07,
                  // width: wight*0.8,
                  child: Stack(
                    children: [
                      Align(
                        alignment: Alignment.center,
                        child: Text(
                          S.of(context).setting_,
                          style: TextStyle(
                              overflow: TextOverflow.ellipsis,
                              fontWeight: FontWeight.bold,
                              fontSize: ScreenUtil().setSp(20),
                              color: Color.fromRGBO(255, 255, 255, 1)),
                          maxLines: 1,
                        ),
                      ),
                      Align(
                          //关闭
                          alignment: Alignment.centerRight,
                          child: GestureDetector(
                            onTap: () {
                              _playAudio();
                              Navigator.pop(context);
                            },
                            child: Image.asset(
                              'assets/images/close.png',
                              fit: BoxFit.contain,
                              width: wight * 0.07,
                              height: hight * 0.05,
                            ),
                          )),
                    ],
                  ),
                ), //
                SizedBox(
                  height: hight * 0.02,
                ),
                getSeing(),
                SizedBox(
                  height: hight * 0.03,
                ),
                getBotton(),
                SizedBox(
                  height: hight * 0.04,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

//定义方法
  _launchURL(url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  /**
   * 底部
   */
  Widget getBotton() {
    double wight = CommUtils.getWidth(context);
    double hight = CommUtils.getHeight(context);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        GestureDetector(
          onTap: () {
            _playAudio();
            if (UniversalPlatform.isWeb) {
              _launchURL(AppConst.serverUrl);
            } else {
              startPageDown(
                  context,
                  WebPage(
                      titel: S.current.erms_of_service,
                      url: AppConst.serverUrl));
            }
          },
          child: Container(
            padding: EdgeInsets.only(left: wight * 0.007, right: wight * 0.007),
            width: hight * 0.15,
            height: hight * 0.04,
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage('assets/images/button_blue.png'),
                  fit: BoxFit.fill),
            ),
            alignment: Alignment.center,
            child: CommUtils.getTextGame(
              context,
              13,
              S.current.erms_of_service,
              colorList[0],
              colorList[1],
            ),
          ),
        ), //服务条款

        AutoSizeText(
          Verison ?? "",
          style: TextStyle(
            fontSize: ScreenUtil().setSp(13),
            fontWeight: FontWeight.bold,
            color: Color.fromRGBO(255, 255, 255, 1),
            height: 0.7,
          ),
          maxLines: 2,
          textAlign: TextAlign.center,
          overflow: TextOverflow.ellipsis,
        ),

        GestureDetector(
          onTap: () {
            _playAudio();
            //跳转
            if (UniversalPlatform.isWeb) {
              _launchURL(AppConst.PrivacyAgreementUrl);
            } else {
              startPageDown(
                  context,
                  WebPage(
                      titel: S.current.Privacy_agreement,
                      url: AppConst.PrivacyAgreementUrl));
            }
          },
          child: Container(
            padding: EdgeInsets.only(left: wight * 0.005, right: wight * 0.005),
            width: hight * 0.15,
            height: hight * 0.04,
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage('assets/images/button_blue.png'),
                  fit: BoxFit.fill),
            ),
            alignment: Alignment.center,
            child: CommUtils.getTextGame(
              context,
              13,
              S.current.Privacy_agreement,
              colorList[0],
              colorList[1],
            ),
          ),
        ), //隐私政策
      ],
    );
  }

/**
 * 中间的设置
 */
  Widget getSeing() {
    double wight = CommUtils.getWidth(context);
    double height = CommUtils.getHeight(context);
    return Container(
      width: double.infinity,
      // height: height * 0.5,
      decoration: BoxDecoration(
        image: DecorationImage(
            image: AssetImage('assets/images/middle.png'), fit: BoxFit.fill),
      ),
      child: Padding(
        padding: EdgeInsets.only(
            top: height * 0.04,
            bottom: height * 0.04,
            left: wight * 0.05,
            right: wight * 0.05),
        child: Column(children: [
          getVoice(height), //音效
          SizedBox(
            height: boxDistance,
          ),
          Image.asset(
            'assets/images/line.png',
            fit: BoxFit.fill,
          ),
          getBGVoice(height), //背景音乐
          SizedBox(
            height: boxDistance,
          ),
          Image.asset(
            'assets/images/line.png',
            fit: BoxFit.fill,
          ),

          SizedBox(
            height: boxDistance,
          ),

          getLanges(height), //语言
          SizedBox(
            height: boxDistance,
          ),
          Image.asset(
            'assets/images/line.png',
            fit: BoxFit.fill,
          ),
          SizedBox(
            height: boxDistance,
          ),
          getTutorial(height), //教程
          SizedBox(
            height: boxDistance,
          ),
          Image.asset(
            'assets/images/line.png',
            fit: BoxFit.fill,
          ),
          widget.isReStart
              ? Column(
                  children: [
                    SizedBox(
                      height: boxDistance,
                    ),
                    reStart(height), //重新开始
                    SizedBox(
                      height: boxDistance,
                    ),
                    Image.asset(
                      'assets/images/line.png',
                      fit: BoxFit.fill,
                    ),
                  ],
                )
              : Text(''),
        ]),
      ),
    );
  }

  Widget getVoice(double height) {
    double wight = CommUtils.getWidth(context);

    return Row(
      children: [
        Image.asset('assets/images/voice.png',
            width: wight * 0.06, height: height * 0.03, fit: BoxFit.contain),
        SizedBox(
          width: wight * 0.03,
        ),
        Text(
          S.of(context).voice_,
          style: TextStyle(
              overflow: TextOverflow.ellipsis,
              fontWeight: FontWeight.bold,
              fontSize: ScreenUtil().setSp(13),
              color: Color.fromRGBO(255, 255, 255, 1)),
          maxLines: 1,
        ),
        Expanded(child: SizedBox()),
        Transform.scale(
          scale: 0.9,
          child: CupertinoSwitch(
              value: _isVoice,
              activeColor: Colors.green, //开关打开时，轨道颜色
              trackColor: Colors.black, //开关关闭时，轨道颜色
              thumbColor: Colors.blue[300], //滑块颜色
              onChanged: (value) {
                setState(() {
                  SpUtils.getInstance()?.setBool(AppConst.voice, value);
                  _isVoice = value;
                  _playAudio();
                  if (widget.callback != null) {
                    widget.callback!(1);
                  }
                });
              }),
        )
      ],
    );
  }

/**
 * 背景音乐
 */
  Widget getBGVoice(double height) {
    double wight = CommUtils.getWidth(context);
    return Row(
      children: [
        Image.asset('assets/images/bg_voice.png',
            width: wight * 0.06, height: height * 0.03, fit: BoxFit.contain),
        SizedBox(
          width: wight * 0.03,
        ),
        Text(
          S.of(context).bg_voice,
          style: TextStyle(
              overflow: TextOverflow.ellipsis,
              fontWeight: FontWeight.bold,
              fontSize: ScreenUtil().setSp(13),
              color: Color.fromRGBO(255, 255, 255, 1)),
          maxLines: 1,
        ),
        Expanded(child: SizedBox()),
        Transform.scale(
          scale: 0.9,
          child: CupertinoSwitch(
              value: _isBGvocie!,
              activeColor: Colors.green, //开关打开时，轨道颜色
              trackColor: Colors.black, //开关关闭时，轨道颜色
              thumbColor: Colors.blue[300], //滑块颜色
              onChanged: (value) {
                setState(() {
                  SpUtils.getInstance()?.setBool(AppConst.bgvoice, value);
                  _isBGvocie = value;
                  if (widget.callback != null) {
                    widget.callback!(1);
                  }
                });
              }),
        )
      ],
    );
  }

/**
 * 语言
 */
  Widget getLanges(double height) {
    double wight = CommUtils.getWidth(context);
    return Row(
      children: [
        Image.asset('assets/images/language.png',
            width: wight * 0.06, height: height * 0.03, fit: BoxFit.contain),
        SizedBox(
          width: wight * 0.03,
        ),
        Text(
          S.of(context).language_,
          style: TextStyle(
              overflow: TextOverflow.ellipsis,
              fontWeight: FontWeight.bold,
              fontSize: ScreenUtil().setSp(13),
              color: Color.fromRGBO(255, 255, 255, 1)),
          maxLines: 1,
        ),
        Expanded(child: SizedBox()),
        GestureDetector(
          onTap: () {
            _playAudio();
            //弹出语言选择款
            if (ClickUtils.checkClick()) {
              showGeneralDialog(
                  context: context,
                  pageBuilder: (context, anim1, anim2) {
                    return Text("");
                  },
                  // barrierColor: Colors.grey.withOpacity(.4), // Dialog 的背景色
                  barrierDismissible: true, //控制 Dialog 是否消失
                  barrierLabel: "",
                  transitionDuration: Duration(milliseconds: 200),
                  transitionBuilder: (context, anim1, anim2, child) {
                    return Transform.scale(
                      scale: anim1.value,
                      child: Dialog(
                        backgroundColor: Colors.transparent,
                        child: LanguagePage(
                          callback: widget.callback,
                        ),
                      ),
                    );
                  });
            }
          },
          child: Container(
            width: height * 0.12,
            height: height * 0.05,
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage('assets/images/button_blue.png'),
                  fit: BoxFit.fill),
            ),
            alignment: Alignment.center,
            child: CommUtils.getTextGame(
              context,
              13,
              S.of(context).change_,
              colorList[0],
              colorList[1],
            ),
          ),
        ),
      ],
    );
  }

  /**
  * 教程
  */
  Widget getTutorial(double height) {
    double wight = CommUtils.getWidth(context);
    return Row(
      children: [
        Image.asset('assets/images/tutorial.png',
            width: wight * 0.06, height: height * 0.03, fit: BoxFit.contain),
        SizedBox(
          width: wight * 0.03,
        ),
        Text(
          S.of(context).jiaocheng_,
          style: TextStyle(
              overflow: TextOverflow.ellipsis,
              fontWeight: FontWeight.bold,
              fontSize: ScreenUtil().setSp(13),
              color: Color.fromRGBO(255, 255, 255, 1)),
          maxLines: 1,
        ),
        Expanded(child: SizedBox()),
        GestureDetector(
          onTap: () {
            _playAudio();
            startPageDown(context, HelpPage());
          },
          child: Container(
            width: height * 0.12,
            height: height * 0.05,
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage('assets/images/button_blue.png'),
                  fit: BoxFit.fill),
            ),
            alignment: Alignment.center,
            child: CommUtils.getTextGame(
              context,
              13,
              S.of(context).see_,
              colorList[0],
              colorList[1],
            ),
          ),
        ),
      ],
    ); //教程
  }

  /**
  * 重新开始
  */
  Widget reStart(double height) {
    double wight = CommUtils.getWidth(context);
    return Row(
      children: [
        Image.asset('assets/images/restart.png',
            width: wight * 0.06, height: height * 0.03, fit: BoxFit.contain),
        SizedBox(
          width: wight * 0.03,
        ),
        Text(
          S.of(context).start_again,
          style: TextStyle(
              overflow: TextOverflow.ellipsis,
              fontWeight: FontWeight.bold,
              fontSize: ScreenUtil().setSp(13),
              color: Color.fromRGBO(255, 255, 255, 1)),
          maxLines: 1,
        ),
        Expanded(child: SizedBox()),
        GestureDetector(
          onTap: () {
            _playAudio();
            //重新开始
            if (widget.callback != null) {
              widget.callback!(8);
            }
            Navigator.pop(context);
          },
          child: Container(
            width: height * 0.12,
            height: height * 0.05,
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage('assets/images/button_blue.png'),
                  fit: BoxFit.fill),
            ),
            alignment: Alignment.center,
            child: CommUtils.getTextGame(
              context,
              13,
              S.of(context).good_2,
              colorList[0],
              colorList[1],
            ),
          ),
        ),
      ],
    ); //教程
  }

  /**
 * 播放音乐
 */
  void _playAudio() {
    if (_isVoice) {
      AudioUtils?.getInstance()?.play("seting_.mp3");
    }
  }
}
